﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Data.SQLite;

namespace TimeTableTool
{
    class LineDao
    {
        private SQLiteConnection connection;

        public LineDao(SQLiteConnection connection)
        {
            this.connection = connection;
        }

        public LineDTO GetLine(int lineId)
        {
            SQLiteCommand command = new SQLiteCommand(connection);
            command.CommandText = "SELECT * FROM line WHERE id=@idValue";
            command.Parameters.AddWithValue("idValue", lineId);

            List<LineDTO> lineList = GetLines(command);
            if (lineList.Count == 1)
            {
                return lineList[0];
            }
            else
            {
                if (lineList.Count < 1)
                {
                    return null;
                }
                else
                {
                    throw new ArgumentException("Something went terribly wrong while searching timetables");
                }
            }
        }

        public void insertLine(int id, String name)
        {
            SQLiteCommand inserCmnd = new SQLiteCommand(connection);
            inserCmnd.CommandText = "INSERT INTO line (id, name) VALUES (@idValue, @nameValue)";
            inserCmnd.Parameters.AddWithValue("idValue", id);
            inserCmnd.Parameters.AddWithValue("nameValue", name);
            inserCmnd.ExecuteNonQuery();
        }

        private List<LineDTO> GetLines(SQLiteCommand cmnd)
        {
            using (cmnd)
            {
                using (SQLiteDataReader reader = cmnd.ExecuteReader())
                {
                    List<LineDTO> lineList = new List<LineDTO>();
                    while (reader.Read())
                    {
                        LineDTO line = new LineDTO();
                        line.Name = reader["name"].ToString();
                        line.Id = int.Parse(reader["id"].ToString());
                        line.Type = reader["type"].ToString();
                        lineList.Add(line);

                    }
                    return lineList;
                }

            }
        }


    }
}
